import { Router } from '../router'
import { cond, NotFoundError, BadRequestError, UnauthorizedError } from '../error'
import { User, UserDb, Message, MessageDb } from '../db'
import conf from '../config'
import * as GitHub from 'github-api'
import * as https from 'https'
import * as fs from 'fs'
import * as path from 'path'
import * as mysql from 'mysql'

var router = new Router()
export default router

export var mysqlClient = mysql.createPool(conf.mysqlClient)

router.get('/message/:id', async (req, res) => {
  cond(req.cookies.accessToken, BadRequestError)
  var userdb = new UserDb(mysqlClient)
  var messageDb = new MessageDb(mysqlClient)
  var user = await userdb.find(req.cookies.accessToken)
  cond(user !== null, UnauthorizedError)
  var message = await messageDb.find(req.uri.query.messageId)
  cond(message !== null, NotFoundError)
  res.writeHead(200, {
    'Content-Type': 'application/join'
  })
  res.end(JSON.stringify(message))
})

router.get('/:userId/messages', async (req, res) => {
  cond(req.cookies.accessToken, BadRequestError)
  var messageDb = new MessageDb(mysqlClient)
  var messages = await messageDb.findAll(req.params.userId)
  res.writeHead(200, {
    'Content-Type': 'application/join'
  })
  res.end(JSON.stringify(messages))
})

router.post('/:userId/message', async (req, res) => {
  cond(req.cookies.accessToken, BadRequestError)
  var userdb = new UserDb(mysqlClient)
  var messageDb = new MessageDb(mysqlClient)
  var user = await userdb.find(req.cookies.accessToken)
  cond(user !== null, UnauthorizedError)
  var messageId = await messageDb.add(req.params.userId, req.fields.title, req.fields.content)
  res.writeHead(201)
  res.end()
})

router.put('/message/:id', async (req, res) => {
  cond(req.cookies.accessToken, BadRequestError)
  var userdb = new UserDb(mysqlClient)
  var messageDb = new MessageDb(mysqlClient)
  var user = await userdb.find(req.cookies.accessToken)
  cond(user !== null, UnauthorizedError)
  await messageDb.update(req.fields.messageId, req.fields.title, 
                         req.fields.content)
  res.writeHead(200)
  res.end()
})

router.delete('/:userId/message', async (req, res) => {
  cond(req.cookies.accessToken, BadRequestError)
  var userdb = new UserDb(mysqlClient)
  var messageDb = new MessageDb(mysqlClient)
  var user = await userdb.find(req.cookies.accessToken)
  cond(user !== null, UnauthorizedError)
  await messageDb.del(req.fields.messageId)
  res.writeHead(200)
  res.end()
})